package com.salinity.kun.other;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;



public class FileHandle {
	public static void main(String[] args) {

//		String filePath = "C:\\Users\\Administrator\\Desktop\\xiazhi_cst.txt";
//		String outPath = "C:\\Users\\Administrator\\Desktop\\xiazhi_cst_out.bln";

		
		String filePath = args[0];
		String outPath = args[1];
		
		File file = new File(filePath);
		File out = new File(outPath);
		if(!file.exists()) {
			System.out.println("file "+filePath +" does not exist!");
			return ;
		}
		
		if(!out.getParentFile().exists()) {
			out.getParentFile().mkdirs();
		}
		
		if(out.exists()) {
			out.delete();
		}
		try {
			out.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try(BufferedReader br = new BufferedReader(new FileReader(file));
				BufferedWriter bw = new BufferedWriter(new FileWriter(out))){
			
			String line = null;
			String[] strArray = null;
			int tempCount = 0,i;
			StringBuilder sb = new StringBuilder();
			String tempFirstLine = "";

			while((line=br.readLine())!=null) {
				strArray = line.trim().split("\\s+");
				if(strArray.length==2) {
					tempCount = Integer.parseInt(strArray[0]);
				}else {
					continue;
				}
				
				//写入head
				
				sb.delete(0, sb.length());
				sb.append(tempCount+1).append(" ").append(strArray[1]);
				bw.write(sb.toString());
				bw.newLine();
				//记录第一行,写入原数据
				for(i=0;i<tempCount;i++) {
					if((line=br.readLine())!=null) {
						if(i==0) {
							tempFirstLine = line;
						}
						
						bw.write(line);
						bw.newLine();
					}else {
						System.out.println("number of data count is not correct!");
						return ;
					}
				}
				
				//将第一行再次追加
				bw.write(tempFirstLine);
				bw.newLine();
			}
			
			System.out.println("complete...");
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
